using UnityEngine;

[ExecuteInEditMode]
public class CameraController : MonoBehaviour
{
    [Header("旋转设置")]
    public float rotationSpeed = 40f; // 旋转速度(度/秒)
    private int rotateDirection = 0;  // 1=右, -1=左, 0=不转

    [Header("高度设置")]
    public float heightSpeed = 0.3f;    // 上下速度(单位/秒)
    private int heightDirection = 0;  // 1=上, -1=下, 0=不动
    public float minHeight = 0f;
    public float maxHeight = 2f;
    private float targetHeight = 0f;

    [Header("距离设置")]
    public float zoomSpeed = 0.5f;      // 缩放速度(单位/秒)
    private int zoomDirection = 0;    // 1=远, -1=近, 0=不动
    public float minDistance = 1f;
    public float maxDistance = 5f;
    private float targetDistance = 2.5f;

    private Transform camTrans; // 子物体相机

    void Start()
    {
        if (transform.childCount > 0)
            camTrans = transform.GetChild(0);
        else
            Debug.LogWarning("CameraController: 没有找到子物体相机！");
        targetHeight = transform.localPosition.y;
        if (camTrans != null)
            targetDistance = -camTrans.localPosition.z;
    }

    void LateUpdate()
    {
        // 持续旋转
        if (rotateDirection != 0)
            transform.Rotate(0, rotationSpeed * rotateDirection * Time.deltaTime, 0);

        // 持续上下
        if (heightDirection != 0)
        {
            targetHeight += heightSpeed * heightDirection * Time.deltaTime;
            targetHeight = Mathf.Clamp(targetHeight, minHeight, maxHeight);
            Vector3 pos = transform.localPosition;
            pos.y = targetHeight;
            transform.localPosition = pos;
        }

        // 持续远近
        if (zoomDirection != 0 && camTrans != null)
        {
            targetDistance += zoomSpeed * zoomDirection * Time.deltaTime;
            targetDistance = Mathf.Clamp(targetDistance, minDistance, maxDistance);
            Vector3 camPos = camTrans.localPosition;
            camPos.z = -targetDistance;
            camTrans.localPosition = camPos;
        }
    }

    // 旋转API
    public void StartRotateRight() { rotateDirection = 1; }
    public void StartRotateLeft() { rotateDirection = -1; }
    public void StopRotate() { rotateDirection = 0; }

    // 上下API
    public void StartMoveUp() { heightDirection = 1; }
    public void StartMoveDown() { heightDirection = -1; }
    public void StopMoveHeight() { heightDirection = 0; }

    // 远近API
    public void StartZoomOut() { zoomDirection = 1; }
    public void StartZoomIn() { zoomDirection = -1; }
    public void StopZoom() { zoomDirection = 0; }

    // 可选：重置接口
    public void ResetCamera()
    {
        transform.localRotation = Quaternion.identity;
        targetHeight = 0f;
        Vector3 pos = transform.localPosition;
        pos.y = targetHeight;
        transform.localPosition = pos;
        if (camTrans != null)
        {
            targetDistance = 2.5f;
            Vector3 camPos = camTrans.localPosition;
            camPos.z = -targetDistance;
            camTrans.localPosition = camPos;
        }
    }
}